from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from django.core.cache import cache
from .monitoring import PerformanceMonitor, health_check
import time


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def system_metrics(request):
    """获取系统指标"""
    try:
        metrics = PerformanceMonitor.get_system_metrics()
        if metrics:
            return Response({
                'success': True,
                'data': metrics
            })
        else:
            return Response({
                'success': False,
                'message': '无法获取系统指标'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取系统指标失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def database_metrics(request):
    """获取数据库指标"""
    try:
        metrics = PerformanceMonitor.get_database_metrics()
        if metrics:
            return Response({
                'success': True,
                'data': metrics
            })
        else:
            return Response({
                'success': False,
                'message': '无法获取数据库指标'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取数据库指标失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def cache_metrics(request):
    """获取缓存指标"""
    try:
        metrics = PerformanceMonitor.get_cache_metrics()
        if metrics:
            return Response({
                'success': True,
                'data': metrics
            })
        else:
            return Response({
                'success': False,
                'message': '无法获取缓存指标'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取缓存指标失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def performance_metrics(request):
    """获取性能指标"""
    try:
        # 获取最近的性能数据
        current_time = int(time.time())
        performance_data = []
        
        # 获取最近1小时的性能数据
        for i in range(3600):  # 1小时 = 3600秒
            timestamp = current_time - i
            cache_key = f"performance_monitor:*:{timestamp}"
            
            # 这里需要实现更复杂的缓存查询逻辑
            # 简化版本，实际应该使用Redis的pattern匹配
            
        return Response({
            'success': True,
            'data': {
                'recent_performance': performance_data,
                'summary': {
                    'total_requests': len(performance_data),
                    'avg_response_time': sum(p.get('execution_time', 0) for p in performance_data) / len(performance_data) if performance_data else 0,
                    'error_rate': len([p for p in performance_data if p.get('status') == 'error']) / len(performance_data) if performance_data else 0
                }
            }
        })
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取性能指标失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([])  # 健康检查不需要认证
def health_check_view(request):
    """健康检查接口"""
    try:
        health_data = health_check()
        
        status_code = status.HTTP_200_OK
        if health_data['status'] != 'healthy':
            status_code = status.HTTP_503_SERVICE_UNAVAILABLE
        
        return Response(health_data, status=status_code)
    except Exception as e:
        return Response({
            'status': 'unhealthy',
            'error': str(e),
            'timestamp': time.time()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
